package com.xyb.service;

import com.xyb.config.exception.MyException;
import com.xyb.dao.WebUserDao;
import com.xyb.entity.StatusCode;
import com.xyb.entity.UserInfo;
import com.xyb.entity.WebUser;
import com.xyb.utils.JwtUtils;
import com.xyb.vo.LoginUserVo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class LoginService {
    @Resource
    private WebUserDao webUserDao;
    @Resource
    private JwtUtils jwtUtils;

    public UserInfo selectUserInfoByAccount(LoginUserVo vo) {
        WebUser webUser = null;
        if (vo.getIphoneNo() != null) {
            webUser = webUserDao.selectWebUserByIphoneNo(vo.getIphoneNo());
        }
        if (vo.getEmail() != null) {
            webUser = webUserDao.selectWebUserByEmail(vo.getEmail());
        }
        if (webUser == null) {
            throw new MyException(StatusCode.USERNAME_OR_PASSWORD_ERROR_EXCEPTION);
        }
        //todo 密码校验
        //至此一定有 webUser
        JwtUtils.JwtUser jwtUser = JwtUtils.JwtUser.builder()
                .id(Long.toString(webUser.getUserId()))
                .build();
        String token = JwtUtils.getToken(jwtUser);

        UserInfo userInfo = UserInfo.builder()
                .token(token)
                .userInfo(UserInfo.InnerUserInfo.builder()
                        .userId(webUser.getUserId())
                        .userName(webUser.getUserName())
                        .userNickName(webUser.getUserNickName())
                        .iphoneNo(webUser.getIphoneNo())
                        .email(webUser.getEmail())
                        .headPortraitUrl(webUser.getHeadPortraitUrl())
                        .status(webUser.getStatus())
                        .createTime(webUser.getCreateTime())
                        .build())
                .isTmp(false)
                .build();
        return userInfo;
    }
}
